package com.bobgao.my_first_demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobgao.my_first_demo.entity.LoginUserEntity;
import com.bobgao.my_first_demo.exception.BusinessException;
import com.bobgao.my_first_demo.exception.BusinessExceptionCode;
import com.bobgao.my_first_demo.mapper.LoginUserMapper;
import com.bobgao.my_first_demo.req.LoginUserSaveReq;
import com.bobgao.my_first_demo.req.UserLoginReq;
import com.bobgao.my_first_demo.resp.UserLoginResp;
import com.bobgao.my_first_demo.service.LoginUserService;
import com.bobgao.my_first_demo.utils.CopyUtil;
import com.bobgao.my_first_demo.utils.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUserEntity> implements LoginUserService {
    @Resource
    private LoginUserMapper loginUserMapper;
    @Resource
    private SnowFlake snowFlake;
    @Override
    public void register(LoginUserSaveReq req) {
        LoginUserEntity user = CopyUtil.copy(req, LoginUserEntity.class);
        if(ObjectUtils.isEmpty(req.getId())){
            LoginUserEntity userDb = selectByLoginName(req.getLoginName());
            if(ObjectUtils.isEmpty(userDb)){
                user.setId(snowFlake.nextId());
                loginUserMapper.insert(user);
            } else {
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        }else {
            user.setLoginName(null);
            user.setPassword(null);
            user.setEmail(null);
            loginUserMapper.updateById(user);
        }
    }
    @Override
    public UserLoginResp login(UserLoginReq req) {
        LoginUserEntity userDb = selectByLoginName(req.getLoginName());
        if(ObjectUtils.isEmpty(userDb)){
            throw  new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }else {
            if(userDb.getPassword().equals(req.getPassword())){
                UserLoginResp userLoginResp = CopyUtil.copy(userDb, UserLoginResp.class);
                return userLoginResp;
            }else {
                throw  new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
    public LoginUserEntity selectByLoginName(String loginName){
        QueryWrapper<LoginUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(LoginUserEntity::getLoginName,loginName);
        List<LoginUserEntity> userEntityList = loginUserMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(userEntityList)){
            return null;
        }else {
            return userEntityList.get(0);
        }
    }
}
